/*
 * Copyright (c) 2020 - present, Inspur Genersoft Co., Ltd.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *       http://www.apache.org/licenses/LICENSE-2.0
 *
 *  Unless required by applicable law or agreed to in writing, software
 *  distributed under the License is distributed on an "AS IS" BASIS,
 *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *  See the License for the specific language governing permissions and
 *  limitations under the License.
 */

package com.inspur.edp.metadata.rtcustomization.servermanager.utils;

import com.inspur.edp.lcm.metadata.api.service.FileService;
import com.inspur.edp.metadata.rtcustomization.common.CustomizedContentSerializerHelper;
import com.inspur.edp.metadata.rtcustomization.common.CustomizedServiceHelper;
import com.inspur.edp.metadata.rtcustomization.serverapi.CustomizationServerService;
import com.inspur.edp.metadata.rtcustomization.spi.CustomizationExtHandler;
import com.inspur.edp.metadata.rtcustomization.spi.CustomizationSerializer;
import io.iec.edp.caf.commons.utils.SpringBeanUtils;
import java.util.HashMap;
import java.util.Map;

public class MetadataDeployUtils {
	private static CustomizationServerService metadataServerService;
	private static FileService fileService;

	private static Map<String, CustomizationExtHandler> customizationExtHandlerMap = new HashMap<>();

	private static Map<String, CustomizationSerializer> changeSetSerializer = new HashMap<>();

	public static CustomizationExtHandler getCustomizationExtHandler(String type) {
		if (customizationExtHandlerMap.containsKey(type)) {
			return customizationExtHandlerMap.get(type);
		}
		//根据元数据扩展关系链，向下合并，合并后保存
		CustomizationExtHandler manager = CustomizedServiceHelper.getInstance().getManager(type);
		if (manager != null) {
			customizationExtHandlerMap.put(type, manager);
		}
		return manager;
	}

	public static CustomizationServerService getMetadataServerService() {
		if (metadataServerService == null) {
			metadataServerService = SpringBeanUtils.getBean(CustomizationServerService.class);
		}
		return metadataServerService;
	}

	public static FileService getFileService() {
		if (fileService == null) {
			fileService = SpringBeanUtils.getBean(FileService.class);
		}
		return fileService;
	}

	public static CustomizationSerializer getChangeSetSerializer(String type) {
		if (!changeSetSerializer.containsKey(type)) {
			CustomizationSerializer changeSetSerializerManager = CustomizedContentSerializerHelper.getInstance().getManager(type);
			if (changeSetSerializerManager == null) {
				throw new RuntimeException("未能正常获取" + type + "的序列化器，请检查配置");
			}
			changeSetSerializer.put(type, changeSetSerializerManager);
		}

		return changeSetSerializer.get(type);
	}
}
